package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.Product;
import com.intelligent.service.ProductService;
import com.intelligent.mapper.ProductMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
* 产品服务实现
* 提供产品分页查询能力，内部委托给 {@link ProductMapper} 执行关联查询。
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

	@Resource
	private ProductMapper productMapper;

	/**
	 * 分页查询产品（关联单位与仓库名称）。
	 * 仅当筛选条件非空时参与查询条件。
	 */
	@Override
	public IPage<Product> pageProduct(Page<Product> page,
	                                 String productCode,
	                                 String productName,
	                                 String sourceType,
	                                 Integer status) {
		return productMapper.pageProduct(page, productCode, productName, sourceType, status);
	}

	@Override
	public List<Product> exportProductInfoToExcel(String productCode, String productName, String sourceType, Integer status) {
		return productMapper.exportProductInfoToExcel(productCode, productName, sourceType, status);
	}

	@Override
	public boolean createProduct(Product product) {
		if (product == null) {
			return false;
		}
		if (product.getProductCode() == null || product.getProductCode().trim().isEmpty()) {
			product.setProductCode(generateProductCode());
		}
		int affected = productMapper.insertProduct(product);
		return affected > 0;
	}

	@Override
	public boolean updateProduct(Product product) {
		if (product == null || product.getProductId() == null) {
			return false;
		}
		int affected = productMapper.updateProduct(product);
		return affected > 0;
	}

	@Override
	public Product getByIdWithJoin(Long productId) {
		if (productId == null) {
			return null;
		}
		return productMapper.getByIdWithJoin(productId);
	}

	@Override
	public boolean deleteProduct(Long productId) {
		if (productId == null) {
			return false;
		}
		int affected = productMapper.deleteProduct(productId);
		return affected > 0;
	}

	private String generateProductCode() {
		String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		int rand = ThreadLocalRandom.current().nextInt(0, 1000);
		return "P" + timestamp + String.format("%03d", rand);
	}

}






